Page({
  data: {
    ctx: null,
    canvas: null,
    currentTool: '', // 当前选中的工具
    shapes: [], // 所有图形元件
    isDrawing: false,
    startPoint: null,
    showTextEditor: false,
    editingText: '',
    editingShapeId: null,
    draggedShape: null,
    lines: [], // 连接线
    canvasRect: null, // 添加画布位置信息
    toolbarHeight: 0, // Added for the new handleShapeTouchMove method
    draggedLinePoint: null, // 新增：当前正在拖动的线条端点信息
    snapDistance: 15, // 磁吸距离阈值
    resizingShape: null, // 新增：当前正在调整大小的图形信息
    selectedShapeId: null, // 新增：当前选中的图形ID
    showJsonModal: false, // 新增：控制JSON弹窗显示
    jsonData: '', // 新增：JSON数据文本
    history: [], // 新增：操作历史记录
    draggedLine: null, // 新增：当前正在拖动的线条
  },

  onLoad() {
    wx.nextTick(() => {
      this.initCanvas();
      // 获取画布位置信息
      this.getCanvasPosition();
    });
  },

  initCanvas() {
    const query = wx.createSelectorQuery();
    query.select('#drawing-canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        const dpr = wx.getSystemInfoSync().pixelRatio || 1;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);
        
        this.setData({ 
          canvas,
          ctx
        });

        this.drawLines();
      });
  },

  selectTool(e) {
    const tool = e.currentTarget.dataset.tool;
    this.setData({ currentTool: tool });
  },

  // 获取画布位置信息
  getCanvasPosition() {
    const query = wx.createSelectorQuery();
    query.select('.toolbar').boundingClientRect(toolbarRect => {
      query.select('.canvas-container').boundingClientRect(canvasRect => {
        this.setData({ 
          canvasRect,
          toolbarHeight: toolbarRect.height
        });
      }).exec();
    }).exec();
  },

  // 获取图形的磁吸点
  getShapeMagneticPoints(shape) {
    const points = [];
    
    if (shape.type === 'square') {
      // 方形的中心点和四个角点
      const centerX = shape.x + 50;
      const centerY = shape.y + 50;
      points.push(
        { x: centerX, y: centerY, type: 'center' },
        { x: shape.x, y: shape.y, type: 'corner' },
        { x: shape.x + 100, y: shape.y, type: 'corner' },
        { x: shape.x, y: shape.y + 100, type: 'corner' },
        { x: shape.x + 100, y: shape.y + 100, type: 'corner' }
      );
    } else if (shape.type === 'circles') {
      // 重叠圆的中心点
      const centerX = shape.x + 70;
      const centerY = shape.y + 40;
      points.push(
        { x: centerX, y: centerY, type: 'center' },
        { x: centerX - 35, y: centerY, type: 'side' }, // 左圆中心
        { x: centerX + 35, y: centerY, type: 'side' }  // 右圆中心
      );
    }
    
    return points;
  },

  // 查找最近的磁吸点
  findNearestMagneticPoint(point) {
    const { shapes, snapDistance } = this.data;
    let nearestPoint = null;
    let minDistance = snapDistance;

    shapes.forEach(shape => {
      const magneticPoints = this.getShapeMagneticPoints(shape);
      
      magneticPoints.forEach(magPoint => {
        const distance = Math.sqrt(
          Math.pow(point.x - magPoint.x, 2) + 
          Math.pow(point.y - magPoint.y, 2)
        );
        
        if (distance < minDistance) {
          minDistance = distance;
          nearestPoint = magPoint;
        }
      });
    });

    return nearestPoint;
  },

  // 保存当前状态到历史记录
  saveToHistory() {
    const currentState = {
      shapes: JSON.parse(JSON.stringify(this.data.shapes)),
      lines: JSON.parse(JSON.stringify(this.data.lines))
    };
    
    const history = this.data.history.slice();
    history.push(currentState);
    
    // 限制历史记录的数量，避免内存占用过大
    if (history.length > 20) {
      history.shift();
    }
    
    this.setData({ history });
  },

  // 处理回退操作
  handleUndo() {
    const { history } = this.data;
    if (history.length === 0) {
      wx.showToast({
        title: '没有可撤销的操作',
        icon: 'none'
      });
      return;
    }

    // 获取上一个状态
    const previousState = history[history.length - 1];
    
    // 更新当前状态
    this.setData({
      shapes: previousState.shapes,
      lines: previousState.lines,
      history: history.slice(0, -1) // 移除最后一个历史记录
    }, () => {
      // 重绘画布
      this.drawLines();
    });
  },

  // 处理画布触摸事件 - 用于绘制线条和创建图形
  handleCanvasTouchStart(e) {
    const { currentTool, canvasRect, toolbarHeight } = this.data;
    if (!currentTool || !canvasRect) return;

    const touch = e.touches[0];
    const x = touch.pageX || touch.x;
    const y = touch.pageY || touch.y;
    
    if (y < toolbarHeight || y > toolbarHeight + canvasRect.height ||
        x < canvasRect.left || x > canvasRect.left + canvasRect.width) {
      return;
    }

    const relativeX = x - canvasRect.left;
    const relativeY = y - toolbarHeight;

    if (currentTool === 'line' || currentTool === 'arrow-line') {
      const nearestPoint = this.findNearestMagneticPoint({ x: relativeX, y: relativeY });
      const startPoint = nearestPoint || { x: relativeX, y: relativeY };
      
      this.setData({
        isDrawing: true,
        startPoint
      });
    } else {
      // 保存当前状态到历史记录
      this.saveToHistory();

      let offsetX = 0, offsetY = 0;
      let width, height;
      
      if (currentTool === 'square') {
        width = 100;
        height = 100;
        offsetX = width / 2;
        offsetY = height / 2;
      } else if (currentTool === 'circles') {
        offsetX = 70;
        offsetY = 40;
      } else if (currentTool === 'text') {
        offsetX = 60;
        offsetY = 40;
      }

      const newShape = {
        id: Date.now().toString(),
        type: currentTool,
        x: relativeX - offsetX,
        y: relativeY - offsetY,
        width,
        height,
        text: currentTool === 'text' ? '双击编辑' : ''
      };

      this.setData({
        shapes: [...this.data.shapes, newShape],
        currentTool: ''
      });

      if (currentTool === 'text') {
        this.handleTextTap({ currentTarget: { dataset: { id: newShape.id } } });
      }
    }
  },

  handleCanvasTouchMove(e) {
    const { isDrawing, startPoint, canvasRect, toolbarHeight } = this.data;
    if (!isDrawing) return;

    const { x, y } = e.touches[0];
    
    // 计算相对于画布的位置
    const relativeX = x - canvasRect.left;
    const relativeY = y - toolbarHeight;

    // 查找最近的磁吸点
    const nearestPoint = this.findNearestMagneticPoint({ x: relativeX, y: relativeY });
    const endPoint = nearestPoint || { x: relativeX, y: relativeY };

    this.drawTempLine(startPoint, endPoint);
  },

  handleCanvasTouchEnd(e) {
    const { isDrawing, startPoint, currentTool, canvasRect, toolbarHeight } = this.data;
    if (!isDrawing) return;

    // 保存当前状态到历史记录
    this.saveToHistory();

    const { x, y } = e.changedTouches[0];
    
    const relativeX = x - canvasRect.left;
    const relativeY = y - toolbarHeight;

    const nearestPoint = this.findNearestMagneticPoint({ x: relativeX, y: relativeY });
    const endPoint = nearestPoint || { x: relativeX, y: relativeY };

    const newLine = {
      id: Date.now().toString(),
      type: currentTool,
      start: { ...startPoint },
      end: endPoint
    };

    this.setData({
      lines: [...this.data.lines, newLine],
      isDrawing: false,
      startPoint: null,
      currentTool: ''
    });

    this.drawLines();
  },

  // 处理图形拖动事件
  handleShapeTouchStart(e) {
    const { id } = e.currentTarget.dataset;
    const touch = e.touches[0];
    const shape = this.data.shapes.find(s => s.id === id);
    const { canvasRect, toolbarHeight } = this.data;
    
    if (!shape || !canvasRect) return;

    // 设置选中的图形
    this.setData({ selectedShapeId: id });

    // 计算触摸点相对于画布的位置
    const touchX = touch.pageX - canvasRect.left;
    const touchY = touch.pageY - toolbarHeight;

    // 计算触摸点相对于形状的偏移量
    const offsetX = touchX - shape.x;
    const offsetY = touchY - shape.y;

    this.setData({
      draggedShape: {
        id,
        offsetX,
        offsetY,
        initialShapeX: shape.x,
        initialShapeY: shape.y
      }
    });
  },

  handleShapeTouchMove(e) {
    const { draggedShape, canvasRect, toolbarHeight, shapes } = this.data;
    if (!draggedShape || !canvasRect) return;

    const touch = e.touches[0];
    const x = touch.pageX || touch.x;
    const y = touch.pageY || touch.y;
    
    let newX = x - canvasRect.left - draggedShape.offsetX;
    let newY = y - toolbarHeight - draggedShape.offsetY;

    const currentShape = this.data.shapes.find(s => s.id === draggedShape.id);
    if (!currentShape) return;

    let shapeWidth = currentShape.width || 100;
    let shapeHeight = currentShape.height || 100;
    
    if (currentShape.type === 'circles') {
      shapeWidth = currentShape.width || 140;
      shapeHeight = currentShape.height || 80;
    } else if (currentShape.type === 'text') {
      shapeWidth = 120;
      shapeHeight = 80;
    }

    // 限制在画布范围内
    newX = Math.max(0, Math.min(newX, canvasRect.width - shapeWidth));
    newY = Math.max(0, Math.min(newY, canvasRect.height - shapeHeight));

    // 检查新位置是否会导致重叠
    if (this.checkOverlapWithOtherShapes(currentShape, newX, newY, shapeWidth, shapeHeight)) {
      return; // 如果会重叠，则不更新位置
    }

    const newShapes = this.data.shapes.map(shape => {
      if (shape.id === draggedShape.id) {
        return {
          ...shape,
          x: newX,
          y: newY
        };
      }
      return shape;
    });

    this.setData({ shapes: newShapes });
  },

  handleShapeTouchEnd() {
    if (this.data.draggedShape) {
      // 保存当前状态到历史记录
      this.saveToHistory();
    }
    this.setData({ draggedShape: null });
  },

  drawTempLine(start, end) {
    const { ctx, canvas, currentTool } = this.data;
    if (!ctx || !canvas) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    this.drawLines();

    ctx.beginPath();
    ctx.moveTo(start.x, start.y);
    ctx.lineTo(end.x, end.y);
    ctx.strokeStyle = '#666';
    ctx.lineWidth = 2;
    ctx.stroke();

    if (currentTool === 'arrow-line') {
      this.drawArrow(ctx, start, end);
    }
  },

  drawArrow(ctx, start, end) {
    const headlen = 10;
    const angle = Math.atan2(end.y - start.y, end.x - start.x);

    ctx.beginPath();
    ctx.moveTo(
      end.x - headlen * Math.cos(angle - Math.PI / 6),
      end.y - headlen * Math.sin(angle - Math.PI / 6)
    );
    ctx.lineTo(end.x, end.y);
    ctx.lineTo(
      end.x - headlen * Math.cos(angle + Math.PI / 6),
      end.y - headlen * Math.sin(angle + Math.PI / 6)
    );
    ctx.strokeStyle = '#666';
    ctx.lineWidth = 2;
    ctx.stroke();
  },

  drawLines() {
    const { ctx, canvas, lines } = this.data;
    if (!ctx || !canvas || !lines.length) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    lines.forEach(line => {
      ctx.beginPath();
      ctx.moveTo(line.start.x, line.start.y);
      ctx.lineTo(line.end.x, line.end.y);
      ctx.strokeStyle = '#666';
      ctx.lineWidth = 2;
      ctx.stroke();

      if (line.type === 'arrow-line') {
        this.drawArrow(ctx, line.start, line.end);
      }
    });
  },

  handleTextTap(e) {
    const { id } = e.currentTarget.dataset;
    const shape = this.data.shapes.find(s => s.id === id);
    
    this.setData({
      showTextEditor: true,
      editingText: shape.text || '',
      editingShapeId: id
    });
  },

  handleTextConfirm(e) {
    const { editingShapeId, shapes } = this.data;
    const newText = e.detail.value;

    // 保存当前状态到历史记录
    this.saveToHistory();

    const newShapes = shapes.map(shape => {
      if (shape.id === editingShapeId) {
        return { ...shape, text: newText };
      }
      return shape;
    });

    this.setData({
      shapes: newShapes,
      showTextEditor: false,
      editingText: '',
      editingShapeId: null
    });
  },

  handleTextBlur() {
    this.setData({
      showTextEditor: false,
      editingText: '',
      editingShapeId: null
    });
  },

  handleClearAll() {
    wx.showModal({
      title: '确认清除',
      content: '是否清除画板上的所有内容？',
      success: (res) => {
        if (res.confirm) {
          // 清除所有图形
          this.setData({
            shapes: [],
            lines: []
          });
          
          // 清除画布
          const { ctx, canvas } = this.data;
          if (ctx && canvas) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
          }
        }
      }
    });
  },

  // 保存功能
  async handleSave() {
    try {
      // 1. 保存为JSON
      const data = {
        shapes: this.data.shapes,
        lines: this.data.lines
      };
      const jsonStr = JSON.stringify(data);
      
      // 保存JSON到本地
      await wx.setStorage({
        key: 'drawingData',
        data: jsonStr
      });

      // 2. 保存为图片
      const { canvas } = this.data;
      if (!canvas) return;

      // 先绘制所有内容到画布
      this.drawAll();

      // 保存画布为图片
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.canvasToTempFilePath({
          canvas,
          success: (res) => resolve(res.tempFilePath),
          fail: reject
        });
      });

      // 保存图片到相册
      await wx.saveImageToPhotosAlbum({
        filePath: tempFilePath
      });

      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('Save error:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  // 加载功能
  async handleLoad() {
    try {
      // 从本地存储加载JSON数据
      const { data: jsonStr } = await wx.getStorage({ key: 'drawingData' });
      const data = JSON.parse(jsonStr);

      // 更新画布内容
      this.setData({
        shapes: data.shapes || [],
        lines: data.lines || []
      }, () => {
        // 重绘所有内容
        this.drawAll();
      });

      wx.showToast({
        title: '加载成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('Load error:', error);
      wx.showToast({
        title: '没有找到保存的数据',
        icon: 'none'
      });
    }
  },

  // 绘制所有内容到画布
  drawAll() {
    const { ctx, canvas, shapes } = this.data;
    if (!ctx || !canvas) return;

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制线条
    this.drawLines();

    // 如果需要，还可以在这里绘制其他内容
  },

  // 处理线条端点的触摸事件
  handleLinePointTouchStart(e) {
    const { id, point } = e.currentTarget.dataset;
    const touch = e.touches[0];
    const { canvasRect, toolbarHeight } = this.data;
    
    if (!canvasRect) return;

    this.setData({
      draggedLinePoint: {
        lineId: id,
        pointType: point, // 'start' 或 'end'
      }
    });
  },

  handleLinePointTouchMove(e) {
    const { draggedLinePoint, canvasRect, toolbarHeight, lines } = this.data;
    if (!draggedLinePoint || !canvasRect) return;

    const touch = e.touches[0];
    const x = touch.pageX || touch.x;
    const y = touch.pageY || touch.y;

    const relativeX = x - canvasRect.left;
    const relativeY = y - toolbarHeight;

    // 查找最近的磁吸点
    const nearestPoint = this.findNearestMagneticPoint({ x: relativeX, y: relativeY });
    const newPoint = nearestPoint || { x: relativeX, y: relativeY };

    // 更新线条端点位置
    const newLines = lines.map(line => {
      if (line.id === draggedLinePoint.lineId) {
        return {
          ...line,
          [draggedLinePoint.pointType]: newPoint
        };
      }
      return line;
    });

    this.setData({ lines: newLines });
    this.drawLines();
  },

  handleLinePointTouchEnd() {
    if (this.data.draggedLinePoint) {
      // 保存当前状态到历史记录
      this.saveToHistory();
    }
    this.setData({ draggedLinePoint: null });
  },

  // 添加磁吸点的可视化（调试用）
  drawMagneticPoints(ctx) {
    const { shapes } = this.data;
    
    shapes.forEach(shape => {
      const points = this.getShapeMagneticPoints(shape);
      points.forEach(point => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 3, 0, Math.PI * 2);
        ctx.fillStyle = point.type === 'center' ? '#ff0000' : '#0000ff';
        ctx.fill();
      });
    });
  },

  // 处理开始调整大小
  handleResizeStart(e) {
    const { id, handle } = e.currentTarget.dataset;
    const touch = e.touches[0];
    const shape = this.data.shapes.find(s => s.id === id);
    
    if (!shape) return;

    // 记录调整大小的初始信息
    this.setData({
      resizingShape: {
        id,
        handle,
        initialX: shape.x,
        initialY: shape.y,
        initialWidth: shape.width || 100,
        initialHeight: shape.height || 100,
        startX: touch.pageX,
        startY: touch.pageY
      }
    });
  },

  // 检查两个图形是否重叠
  checkShapesOverlap(shape1, shape2) {
    // 获取第一个图形的边界
    const bounds1 = this.getShapeBounds(shape1);
    // 获取第二个图形的边界
    const bounds2 = this.getShapeBounds(shape2);

    // 检查边界是否重叠
    return !(bounds1.right < bounds2.left || 
             bounds1.left > bounds2.right || 
             bounds1.bottom < bounds2.top || 
             bounds1.top > bounds2.bottom);
  },

  // 获取图形的边界
  getShapeBounds(shape) {
    let bounds = {
      left: shape.x,
      top: shape.y,
      right: shape.x + (shape.width || 100),
      bottom: shape.y + (shape.height || 100)
    };

    if (shape.type === 'circles') {
      bounds.right = shape.x + (shape.width || 140);
      bounds.bottom = shape.y + (shape.height || 80);
    }

    return bounds;
  },

  // 检查新位置是否会导致与其他图形重叠
  checkOverlapWithOtherShapes(currentShape, newX, newY, newWidth, newHeight) {
    const testShape = {
      ...currentShape,
      x: newX,
      y: newY,
      width: newWidth,
      height: newHeight
    };

    return this.data.shapes.some(shape => {
      if (shape.id === currentShape.id) return false;
      return this.checkShapesOverlap(testShape, shape);
    });
  },

  // 更新 handleResizeMove
  handleResizeMove(e) {
    const { resizingShape, canvasRect } = this.data;
    if (!resizingShape || !canvasRect) return;

    const touch = e.touches[0];
    const deltaX = touch.pageX - resizingShape.startX;
    const deltaY = touch.pageY - resizingShape.startY;

    let newX = resizingShape.initialX;
    let newY = resizingShape.initialY;
    let newWidth = resizingShape.initialWidth;
    let newHeight = resizingShape.initialHeight;

    const currentShape = this.data.shapes.find(s => s.id === resizingShape.id);
    if (!currentShape) return;

    // 设置最小尺寸
    const minWidth = currentShape.type === 'circles' ? 100 : 50;
    const minHeight = currentShape.type === 'circles' ? 60 : 50;

    // 根据不同的控制点计算新的位置和大小
    switch (resizingShape.handle) {
      case 'top-left':
        newX = Math.min(resizingShape.initialX + resizingShape.initialWidth - minWidth, 
                       resizingShape.initialX + deltaX);
        newY = Math.min(resizingShape.initialY + resizingShape.initialHeight - minHeight, 
                       resizingShape.initialY + deltaY);
        newWidth = Math.max(minWidth, resizingShape.initialWidth - deltaX);
        newHeight = Math.max(minHeight, resizingShape.initialHeight - deltaY);
        break;
      case 'top-right':
        newY = Math.min(resizingShape.initialY + resizingShape.initialHeight - minHeight, 
                       resizingShape.initialY + deltaY);
        newWidth = Math.max(minWidth, resizingShape.initialWidth + deltaX);
        newHeight = Math.max(minHeight, resizingShape.initialHeight - deltaY);
        break;
      case 'bottom-left':
        newX = Math.min(resizingShape.initialX + resizingShape.initialWidth - minWidth, 
                       resizingShape.initialX + deltaX);
        newWidth = Math.max(minWidth, resizingShape.initialWidth - deltaX);
        newHeight = Math.max(minHeight, resizingShape.initialHeight + deltaY);
        break;
      case 'bottom-right':
        newWidth = Math.max(minWidth, resizingShape.initialWidth + deltaX);
        newHeight = Math.max(minHeight, resizingShape.initialHeight + deltaY);
        break;
    }

    // 限制在画布范围内
    newX = Math.max(0, Math.min(newX, canvasRect.width - newWidth));
    newY = Math.max(0, Math.min(newY, canvasRect.height - newHeight));

    // 检查新尺寸是否会导致重叠
    if (this.checkOverlapWithOtherShapes(currentShape, newX, newY, newWidth, newHeight)) {
      return; // 如果会重叠，则不更新尺寸
    }

    // 更新图形
    const newShapes = this.data.shapes.map(shape => {
      if (shape.id === resizingShape.id) {
        return {
          ...shape,
          x: newX,
          y: newY,
          width: newWidth,
          height: newHeight
        };
      }
      return shape;
    });

    this.setData({ shapes: newShapes });
  },

  // 处理结束调整大小
  handleResizeEnd() {
    if (this.data.resizingShape) {
      // 保存当前状态到历史记录
      this.saveToHistory();
    }
    this.setData({ resizingShape: null });
  },

  // 处理图形点击事件
  handleShapeClick(e) {
    const { id } = e.currentTarget.dataset;
    this.setData({ selectedShapeId: id });
  },

  // 处理画布点击事件，用于取消选中
  handleCanvasClick() {
    if (this.data.selectedShapeId) {
      this.setData({ selectedShapeId: null });
    }
  },

  // 处理查看JSON数据
  handleViewJson() {
    const data = {
      shapes: this.data.shapes,
      lines: this.data.lines
    };
    
    // 格式化JSON数据
    const jsonStr = JSON.stringify(data, null, 2);
    
    this.setData({
      showJsonModal: true,
      jsonData: jsonStr
    });
  },

  // 关闭JSON弹窗
  handleCloseJsonModal() {
    this.setData({
      showJsonModal: false,
      jsonData: ''
    });
  },

  // 处理线条拖动开始
  handleLineTouchStart(e) {
    const { id } = e.currentTarget.dataset;
    const touch = e.touches[0];
    const line = this.data.lines.find(l => l.id === id);
    const { canvasRect, toolbarHeight } = this.data;
    
    if (!line || !canvasRect) return;

    // 设置选中的线条
    this.setData({ selectedShapeId: id });

    // 计算触摸点相对于画布的位置
    const touchX = touch.pageX - canvasRect.left;
    const touchY = touch.pageY - toolbarHeight;

    // 计算触摸点相对于线条起点的偏移量
    this.setData({
      draggedLine: {
        id,
        offsetX: touchX - line.start.x,
        offsetY: touchY - line.start.y,
        // 保存线条端点之间的相对位置
        deltaX: line.end.x - line.start.x,
        deltaY: line.end.y - line.start.y
      }
    });
  },

  // 处理线条拖动
  handleLineTouchMove(e) {
    const { draggedLine, canvasRect, toolbarHeight } = this.data;
    if (!draggedLine || !canvasRect) return;

    const touch = e.touches[0];
    
    // 计算新的起点位置
    let newStartX = touch.pageX - canvasRect.left - draggedLine.offsetX;
    let newStartY = touch.pageY - toolbarHeight - draggedLine.offsetY;

    // 计算新的终点位置（保持相对位置不变）
    let newEndX = newStartX + draggedLine.deltaX;
    let newEndY = newStartY + draggedLine.deltaY;

    // 确保线条在画布范围内
    if (newStartX < 0) {
      newStartX = 0;
      newEndX = draggedLine.deltaX;
    }
    if (newStartX > canvasRect.width) {
      newStartX = canvasRect.width;
      newEndX = newStartX + draggedLine.deltaX;
    }
    if (newStartY < 0) {
      newStartY = 0;
      newEndY = draggedLine.deltaY;
    }
    if (newStartY > canvasRect.height) {
      newStartY = canvasRect.height;
      newEndY = newStartY + draggedLine.deltaY;
    }

    // 更新线条位置
    const newLines = this.data.lines.map(line => {
      if (line.id === draggedLine.id) {
        return {
          ...line,
          start: { x: newStartX, y: newStartY },
          end: { x: newEndX, y: newEndY }
        };
      }
      return line;
    });

    this.setData({ lines: newLines });
    this.drawLines();
  },

  // 处理线条拖动结束
  handleLineTouchEnd() {
    if (this.data.draggedLine) {
      // 保存当前状态到历史记录
      this.saveToHistory();
    }
    this.setData({ draggedLine: null });
  },
}); 